package com.demo.gateway.service.impl;

import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo.gateway.mapper.JobMapper;
import com.demo.gateway.pojo.ScheduleJobDO;
import com.demo.gateway.quartz.ScheduleJobFactory;
import com.demo.gateway.quartz.ScheduleOptType;
import com.demo.gateway.service.IScheduleJob;

import lombok.extern.slf4j.Slf4j;

/**
 * @author: demo
 * @date: 2020年6月28日
 * @Document : 定时服务类
 */
@Slf4j
@Service
public class ScheduleJobService implements IScheduleJob {
	/**
	 * 调度器
	 */
	@Autowired
	private Scheduler scheduler;

	@Autowired
	private JobMapper jobMapper;

	@Override
	public void refreshJobs() {
		List<ScheduleJobDO> databaseJobs = jobMapper.queryStartJobs();
		if (databaseJobs==null||databaseJobs.size()==0) {
		    log.debug("未查询到定时任务!!!");  	
			return ;
		}
		databaseJobs.forEach(job -> addJob(job));
	}

	@Override
	public void addJob(ScheduleJobDO job) {
		try {
			// 创建触发器
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName())
					.withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression())).startNow().build();
			// 创建任务
			JobDetail jobDetail = JobBuilder.newJob(ScheduleJobFactory.class).withIdentity(job.getJobName()).build();
			// 传入调度的数据，在QuartzFactory中需要使用
			jobDetail.getJobDataMap().put("scheduleJob", job);
			// 调度作业
			scheduler.scheduleJob(jobDetail, trigger);
             log.info("{}  start success! cron规则为==>{} ",job.getJobName(),job.getCronExpression());
		} catch (Exception e) {
			log.error(job.getJobName() + "启动失败!", e);
		}
	}

	@Override
	public void operateJob(ScheduleOptType jobOperateEnum, ScheduleJobDO job) throws SchedulerException {
		JobKey jobKey = new JobKey(job.getJobName());
		JobDetail jobDetail = scheduler.getJobDetail(jobKey);
		if (jobDetail == null) {
			throw new SchedulerException("被操作的定时任务不存在!");
		}
		switch (jobOperateEnum) {
		case START:
			scheduler.resumeJob(jobKey);
			break;
		case PAUSE:
			scheduler.pauseJob(jobKey);
			break;
		case DELETE:
			scheduler.deleteJob(jobKey);
			break;
		default:
			log.warn("不支持的定时操作类型!");
			break;
		}

	}

	@Override
	public void startAllJob() throws SchedulerException {
		scheduler.start();
	}

	@Override
	public void pauseAllJob() throws SchedulerException {
		scheduler.standby();
	}

}
